package com.ly.heart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.common.PageParam;
import com.ly.common.annotation.DataScope;
import com.ly.common.core.domain.ActCurrentTaskVo;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.StringUtils;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.CustomerVisitDetailEntity;
import com.ly.heart.domain.CustomerVisitEntity;
import com.ly.heart.domain.FileEntity;
import com.ly.heart.domain.dto.CustomerVisitDto;
import com.ly.heart.domain.dto.StartProcessDto;
import com.ly.heart.domain.vo.CustomerVisitVo;
import com.ly.heart.mapper.CustomerVisitMapper;
import com.ly.heart.service.IActModelService;
import com.ly.heart.service.ICustomerVisitDetailService;
import com.ly.heart.service.ICustomerVisitService;
import com.ly.heart.service.IFileInfoService;
import com.ly.heart.util.CurrentUserUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 客户拜访申请 服务实现类
 * </p>
 *
 * @author WuZH
 * @since 2024-09-29
 */
@Service
public class CustomerVisitServiceImpl extends ServiceImpl<CustomerVisitMapper, CustomerVisitEntity> implements ICustomerVisitService {

    @Resource
    private CustomerVisitMapper customerVisitMapper;
    @Resource
    private ICustomerVisitDetailService iCustomerVisitDetailService;
    @Resource
    private IActModelService iActModelService;
    @Resource
    private IFileInfoService iFileInfoService;

    @Override
    @DataScope ( deptAlias = "sd" )
    public AjaxResult list ( CustomerVisitEntity customerVisitEntity ) {
        customerVisitEntity.setPage ( ( customerVisitEntity.getPage () - 1 ) * customerVisitEntity.getLimit () );
        List<CustomerVisitEntity> customerVisitEntities = customerVisitMapper.selectCustomerVisitList ( customerVisitEntity );
        customerVisitEntities.forEach ( visit -> {
            //任务信息
            ActCurrentTaskVo currentTaskVo = iActModelService.getCurrentTaskByInstanceId ( visit.getInstanceId () );
            Optional.ofNullable ( currentTaskVo ).ifPresent ( currentTask -> {
                visit.setCurrentTask ( currentTask );
            } );
        } );
        Integer integer = customerVisitMapper.selectCustomerVisitCount ( customerVisitEntity );
        PageParam p = new PageParam ();
        p.setRecords ( customerVisitEntities ).setTotal ( integer );
        return AjaxResult.success ( p );
    }

    @Override
    public CustomerVisitVo querySingle ( String id ) {
        CustomerVisitVo vo = new CustomerVisitVo ();
        CustomerVisitDetailEntity visitDetailEntity = new CustomerVisitDetailEntity ();
        visitDetailEntity.setCustomerVisitId ( id );
        List<CustomerVisitDetailEntity> list = iCustomerVisitDetailService.list ( visitDetailEntity );
        List<FileEntity> fileEntities = iFileInfoService.list (new LambdaQueryWrapper<FileEntity> ().eq ( FileEntity::getRelationId, id ) );
        CustomerVisitEntity customerVisitEntity = customerVisitMapper.selectCustomerVisitById ( id );
        customerVisitEntity.setFileEntities ( fileEntities );
        vo.setCustomerVisitEntity ( customerVisitEntity ).setCustomerVisitDetailEntities ( list );
        return vo;
    }

    @Override
    public AjaxResult draft ( CustomerVisitDto customerVisitDto ) {
        CustomerVisitEntity customerVisitEntity = customerVisitDto.getCustomerVisitEntity ();
        customerVisitEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
        int count = this.count ();
        customerVisitEntity.setDocNo ( "KHBF".concat ( String.format ( "%08d", count ) ) );
        customerVisitEntity.setDeptId ( CurrentUserUtil.getCompanyId () );
        customerVisitEntity.setUserId ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
        customerVisitEntity.setCreateTime ( DateUtils.getNowDate () );
        customerVisitEntity.setState ( ConstUtil.STATE_IN_DRAFT );
        updateCustomerVisitDetail ( customerVisitDto.getCustomerVisitDetailEntities (), customerVisitEntity.getId () );
        updateFile ( customerVisitEntity.getFileEntities (), customerVisitEntity.getId () );
        boolean save = this.save ( customerVisitEntity );
        if ( ! save ) {
            throw new CustomException ( "新增客户拜访失败！" );
        }
        return AjaxResult.success ( "暂存客户拜访申请单成功", customerVisitEntity.getId () );
    }

    @Override
    public AjaxResult submit ( CustomerVisitEntity customerVisitEntity ) {
        if ( StringUtils.isBlank ( customerVisitEntity.getId () ) ) {
            return AjaxResult.error ( "请先暂存该单据" );
        }
        StartProcessDto startDto = new StartProcessDto ().
                setBusinessId ( customerVisitEntity.getId () ).
                setBusinessType ( customerVisitEntity.getBusinessType () ).setModelId ( customerVisitEntity.getModelId () ).
                setBusinessName ( "客户拜访申请单".concat ( customerVisitEntity.getId () ) );
        String instanceId = iActModelService.startProcess ( startDto );
        boolean update = this.update ( new LambdaUpdateWrapper<CustomerVisitEntity> ().
                set ( CustomerVisitEntity :: getState, ConstUtil.STATE_IN_PROCESS ).
                set ( CustomerVisitEntity :: getInstanceId, instanceId ).
                eq ( CustomerVisitEntity :: getId, customerVisitEntity.getId () ) );
        if ( ! update ) {
            throw new CustomException ( "提交客户拜访申请单失败！" );
        }
        return AjaxResult.success ();
    }

    @Override
    public AjaxResult updateSingle ( CustomerVisitDto customerVisitDto ) {
        CustomerVisitEntity customerVisitEntity = customerVisitDto.getCustomerVisitEntity ();
        customerVisitEntity.setUpdateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
        customerVisitEntity.setUpdateTime ( DateUtils.getNowDate () );
        updateCustomerVisitDetail ( customerVisitDto.getCustomerVisitDetailEntities (), customerVisitEntity.getId () );
        updateFile ( customerVisitEntity.getFileEntities (), customerVisitEntity.getId () );
        boolean b = this.updateById ( customerVisitEntity );
        if ( ! b ) {
            throw new CustomException ( "修改客户拜访申请单失败！" );
        }
        return AjaxResult.success ();
    }

    @Override
    public AjaxResult deleteSingle ( String id ) {
        boolean update = this.update ( new LambdaUpdateWrapper<CustomerVisitEntity> ().set ( CustomerVisitEntity :: getIsUsed, ConstUtil.IS_USED_NO ).eq ( CustomerVisitEntity :: getId, id ) );
        if ( ! update ) {
            throw new CustomException ( "删除客户拜访申请单失败！" );
        }
        return AjaxResult.success ();
    }

    private void updateCustomerVisitDetail ( List<CustomerVisitDetailEntity> customerVisitDetailEntities, String customerVisitId ) {
        iCustomerVisitDetailService.remove ( new LambdaUpdateWrapper<CustomerVisitDetailEntity> ().eq ( CustomerVisitDetailEntity :: getCustomerVisitId, customerVisitId ) );
        customerVisitDetailEntities.forEach ( detail -> {
            detail.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
            detail.setCustomerVisitId ( customerVisitId );
            detail.setCreateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
            detail.setCreateTime ( DateUtils.getNowDate () );
            boolean save = iCustomerVisitDetailService.save ( detail );
            if ( ! save ) {
                throw new CustomException ( "更新客户拜访礼品明细行失败！" );
            }
        } );
    }

    private void updateFile ( List<FileEntity> fileEntities, String customerVisitId ) {
        if ( ! CollectionUtils.isEmpty ( fileEntities ) ) {
            iFileInfoService.remove ( new LambdaUpdateWrapper<FileEntity> ().eq ( FileEntity :: getRelationId, customerVisitId ) );
            fileEntities.forEach ( file -> {
                file.setRelationId ( customerVisitId );
                iFileInfoService.save ( file );
            } );
        }
    }

}
